package com.glory.gloryquickui.widget.dialog;//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

import android.app.Dialog;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.glory.gloryquickui.R;
import com.glory.gloryquickui.entity.VersionEntity;
import com.glory.gloryquickui.utils.FileUtils;
import com.glory.gloryquickui.utils.FreeApi_ToastUtils;
import com.glory.gloryquickui.utils.InitUtils;
import com.glory.gloryquickui.widget.dialog.anim.FreeUI_Rotate3dAnimation;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;

import java.io.File;
import java.text.DecimalFormat;


public class FreeUI_DownloadFragmentDialog extends AppCompatDialogFragment {
    private VersionEntity versionEntity;
    private Button btnRe;
    private LinearLayout llMain;
    private LinearLayout llDownloadTips;
    private LinearLayout llBottom;
    private RelativeLayout llDownload;
    private ProgressBar progressBar;
    private TextView tvProgress;
    private DownloadTask task;
    private boolean isFinish = false;
    private String fileFolderPath;
    private String savePath;

    public FreeUI_DownloadFragmentDialog() {
        this.fileFolderPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "apk_download";
    }

    public void setData(VersionEntity versionEntity) {
        this.versionEntity = versionEntity;
    }

    public void show(FragmentManager manager, String tag) {
        if (!this.isAdded()) {
            FragmentTransaction ft = manager.beginTransaction();
            ft.add(this, tag);
            ft.commitAllowingStateLoss();
        }

    }

    public void onStart() {
        super.onStart();
        Dialog dialog = this.getDialog();
        if (dialog != null) {
            dialog.getWindow().setLayout((int)((double) InitUtils.Companion.getSCREEN_WIDTH() * 0.8D), -2);
        }

    }

    public void onDestroyView() {
        super.onDestroyView();
        if (this.task != null) {
            this.task.unRegister("down_new_version");
            this.task.remove(!this.isFinish);
        }


    }

    @Nullable
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        int resID = R.layout.blue_sky_dialog_download;
//        if (FreeApi_StaticMembers.CURRENT_THEME != FreeApi_StaticMembers.THEME_DARK_GOLD && FreeApi_StaticMembers.CURRENT_THEME != FreeApi_StaticMembers.THEME_SINGLE_DARK_GOLD) {
//            if (FreeApi_StaticMembers.CURRENT_THEME != FreeApi_StaticMembers.THEME_SKY_BLUE && FreeApi_StaticMembers.CURRENT_THEME != FreeApi_StaticMembers.THEME_SINGLE_SKY_BLUE) {
//                if (FreeApi_StaticMembers.CURRENT_THEME == FreeApi_StaticMembers.THEME_GLORY || FreeApi_StaticMembers.CURRENT_THEME == FreeApi_StaticMembers.THEME_SINGLE_GLORY) {
//                    resID = layout.free_ui_blue_sky_dialog_download;
//                }
//            } else {
//                resID = layout.free_ui_blue_sky_dialog_download;
//            }
//        } else {
//            resID = layout.free_ui_dark_gold_dialog_download;
//        }

        View view = inflater.inflate(resID, null);
        this.getDialog().getWindow().setGravity(17);
        this.getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(0));
        this.getDialog().getWindow().setWindowAnimations(R.style.BottomDialog);
        this.getDialog().setCanceledOnTouchOutside(false);
        this.getDialog().setCancelable(false);
        this.getDialog().setOnKeyListener((dialog, keyCode, event) -> {
            if (keyCode == 4) {
                FreeApi_ToastUtils.showFreeToast("请更新后使用", FreeUI_DownloadFragmentDialog.this.getActivity(), false, 0);
                return true;
            } else {
                return false;
            }
        });
        return view;
    }

    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        TextView tvVersion = view.findViewById(R.id.tvVersion);
        TextView tvCurrentVersion = view.findViewById(R.id.tvCurrentVersion);
        TextView tvDesc = view.findViewById(R.id.tvDesc);
        this.tvProgress = view.findViewById(R.id.tvProgress);
        Button btnConfirm = view.findViewById(R.id.btnConfirm);
        this.btnRe = view.findViewById(R.id.btnRe);
        this.progressBar = view.findViewById(R.id.pbDownload);
        this.llMain = view.findViewById(R.id.llMain);
        this.llDownloadTips = view.findViewById(R.id.llDownloadTips);
        this.llDownload = view.findViewById(R.id.llDownload);
        this.llBottom = view.findViewById(R.id.llBottom);
        tvDesc.setText(this.versionEntity.getDesc());
        tvVersion.setText(String.valueOf(this.versionEntity.getVersion()));
        tvCurrentVersion.setText(String.valueOf(this.versionEntity.getCurrentVersion()));
        this.savePath = this.fileFolderPath + "/" + this.versionEntity.getApkName() + ".apk";
        this.btnRe.setOnClickListener(v -> {
            if (FreeUI_DownloadFragmentDialog.this.task != null) {
                FreeUI_DownloadFragmentDialog.this.task.start();
            }

        });
        btnConfirm.setOnClickListener(view1 -> {
            if ((new File(FreeUI_DownloadFragmentDialog.this.savePath)).exists()) {
                (new File(FreeUI_DownloadFragmentDialog.this.savePath)).delete();
            }

            FreeUI_DownloadFragmentDialog.this.startAnAnimation();
            FreeUI_DownloadFragmentDialog.this.initDownload();
        });
        super.onViewCreated(view, savedInstanceState);
    }

    private void startAnAnimation() {
        LayoutParams lp2 = (LayoutParams)this.llDownload.getLayoutParams();
        lp2.height = this.llDownloadTips.getHeight();
        this.llDownload.setLayoutParams(lp2);
        float centerX = (float)this.llMain.getWidth() / 2.0F;
        float centerY = (float)this.llMain.getHeight() / 2.0F;
        FreeUI_Rotate3dAnimation animation = new FreeUI_Rotate3dAnimation(0.0F, 90.0F, centerX, centerY, 310.0F, true);
        animation.setDuration(200L);
        animation.setInterpolator(new AccelerateInterpolator());
        animation.setFillAfter(true);
        this.llMain.startAnimation(animation);
        animation.setAnimationListener(new AnimationListener() {
            public void onAnimationStart(Animation animation) {
            }

            public void onAnimationEnd(Animation animation) {
                FreeUI_DownloadFragmentDialog.this.llDownloadTips.setVisibility(View.GONE);
                FreeUI_DownloadFragmentDialog.this.llDownload.setVisibility(View.VISIBLE);
                float centerX = (float)FreeUI_DownloadFragmentDialog.this.llMain.getWidth() / 2.0F;
                float centerY = (float)FreeUI_DownloadFragmentDialog.this.llMain.getHeight() / 2.0F;
                FreeUI_Rotate3dAnimation rotation = new FreeUI_Rotate3dAnimation(270.0F, 360.0F, centerX, centerY, 310.0F, false);
                rotation.setDuration(100L);
                rotation.setFillAfter(true);
                rotation.setInterpolator(new AccelerateInterpolator());
                FreeUI_DownloadFragmentDialog.this.llMain.startAnimation(rotation);
                rotation.setAnimationListener(new AnimationListener() {
                    public void onAnimationStart(Animation animation) {
                    }

                    public void onAnimationEnd(Animation animation) {
                        FreeUI_DownloadFragmentDialog.this.task.start();
                    }

                    public void onAnimationRepeat(Animation animation) {
                    }
                });
            }

            public void onAnimationRepeat(Animation animation) {
            }
        });
    }

    private void initDownload() {
        File fileFolder = new File(this.fileFolderPath);
        if (!fileFolder.exists()) {
            fileFolder.mkdirs();
        }

        GetRequest<File> request = OkGo.get(this.versionEntity.getDownUrl());
        this.task = OkDownload.request("down_new_version", request).save().folder(this.fileFolderPath).fileName(this.versionEntity.getApkName() + ".apk").register(new DownloadListener("down_new_version") {
            public void onStart(Progress progress) {
                FreeUI_DownloadFragmentDialog.this.llBottom.setVisibility(View.GONE);
            }

            public void onProgress(Progress progress) {
                FreeUI_DownloadFragmentDialog.this.progressBar.setMax((int)progress.totalSize);
                FreeUI_DownloadFragmentDialog.this.progressBar.setProgress((int)progress.currentSize);
                double current = (double)progress.currentSize * 1.0D;
                double total = (double)progress.totalSize * 1.0D;
                double percent = current / total;
                DecimalFormat df = new DecimalFormat("##%");
                FreeUI_DownloadFragmentDialog.this.tvProgress.setText(df.format(percent));
            }

            public void onError(Progress progress) {
                FreeApi_ToastUtils.showFreeToast(FreeUI_DownloadFragmentDialog.this.getString(R.string.update_fail), FreeUI_DownloadFragmentDialog.this.getActivity(), false, 0);
//                FreeApi_LogUtils.saveErrorMessages(progress.exception, "APK下载失败");
                FreeUI_DownloadFragmentDialog.this.llBottom.setVisibility(View.VISIBLE);
            }

            public void onFinish(File file, Progress progress) {
                FreeUI_DownloadFragmentDialog.this.isFinish = true;
                FreeUI_DownloadFragmentDialog.this.openApk();
                FreeUI_DownloadFragmentDialog.this.dismissAllowingStateLoss();
                FreeApi_ToastUtils.showFreeToast(FreeUI_DownloadFragmentDialog.this.getString(R.string.update_complete), FreeUI_DownloadFragmentDialog.this.getActivity(), true, 0);
            }

            public void onRemove(Progress progress) {
            }
        });
    }

    private void openApk() {
        this.dismiss();
        FileUtils.openFile(this.getActivity(), new File(this.savePath));
    }
}
